/**
 * Definition of RestClient
 */
package org.cholm.drtest;

import java.io.IOException;


import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * A client to do REST GET queries
 *
 *
 * @author cholm
 */
@SuppressWarnings("deprecation")
public class RestClient {
	/**
	 * The result of the query.  It can be an object or an array, but not both.
	 *
	 * @author cholm
	 */
	public static class Result {
		/** Object result */
		public JSONObject object = null;
		/** Array result */
		public JSONArray  array  = null;
	}
	/**
	 * Desctructor called by garbage collector
	 */
	public void finalize()
	{
		if (client != null) {
			log.warn("Client not closed yet!");
			close();
		}
	}
	/**
	 * Close the client
	 */
	public void close() {
		client.getConnectionManager().shutdown();
		client = null;
	}
	/* This is a test function which will connects to a given
	 * rest service and prints it's response the output
	 */
	public Result get(String url)
	{
		// Make client if needed
		if (client == null) client = new DefaultHttpClient();

		// Our return value
		Result json = null;

		// Prepare a request object
		HttpGet get = new HttpGet(url);

		// Execute the request
		try {
			HttpResponse response = client.execute(get);
			// Examine the response status
			log.debug("Response: " + response.getStatusLine().toString());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {
				String result =  EntityUtils.toString(entity);
				// System.out.println(result);
				entity.consumeContent();

				// A Simple JSONObject Creation
				json = new RestClient.Result();
				try {
					json.object = new JSONObject(result);
				} catch (JSONException e) {
					log.warn(e.getMessage());
					json.object = null;
				}
				try {
					if (json.object == null)
						json.array  = new JSONArray(result);
				}  catch (JSONException e) {
					log.warn(e.getMessage());
					json.array = null;
				}
			}
		} catch (ClientProtocolException e) {
			log.error(e.getMessage());
			log.error(e.getStackTrace());
		} catch (IOException e) {
			log.error(e.getMessage());
			log.error(e.getStackTrace());
		} finally {
		    get.releaseConnection();
		}

		// Return to caller
		return json;
	}
	/**
	 * Print retrieved result
	 * @param json
	 */
	public void print(Result json)
	{
		try {
			if (json.object != null)
				log.debug(json.object.toString(2));
			if (json.array != null)
				log.debug(json.array.toString(2));
		} catch (JSONException e) {
			log.error(e.getMessage());
		}
	}
	/** Our log */
	protected Log log = LogFactory.getLog(RestClient.class);
	/** Our client */
	protected HttpClient client = new DefaultHttpClient();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Logger httpLog = Logger.getLogger("org.apache.http");
		if (httpLog != null) httpLog.setLevel(Level.OFF);

		// String url = "http://dr.dk/nu/api/programseries/bamses-billedbog/videos";
		String url = "http://www.dr.dk/mu/programcard/bamses-billedbog";
		RestClient rest = new RestClient();
		Result     ret  = rest.get(url);
		rest.print(ret);
	}

}
// EOF
